<template>
  <div class="header-box">
    <base-header :project-logo="appName ? '' : projectLogo" :project-name="appName" :isNewWindow="false" :user-name="userInfo.nickname || userInfo.name || userInfo.phone" :menu-list="menuList" :dropdown-list="dropdownList" @rightDropClick="handleCommand" :token-key="'token'" @redirect="menuRedirect">
      <!-- 客户详情 -->
      <section v-if="$route.query.clientName" slot="right" class="margin-right-20">{{ $route.query.clientName }}</section>

      <!-- 项目下拉框 -->
      <section v-if="isSelectProject && !isHiddenTools" class="project-select" slot="right">
        <el-select class="header-project" :disabled="projectDisable" v-model="projectName" placeholder="请选择" @change="changeProject(true)">
          <el-option v-for="(item, index) in projectOptions" :key="index" :label="item.projectName" :value="item.projectKey"> </el-option>
        </el-select>
      </section>

      <!-- 计划 -->
      <section v-if="$route.query.planProjectName" class="margin-right-20" slot="right">{{ $route.query.planProjectName }}{{ $route.query.year }}年{{ $route.query.month && $route.query.month + '月' }}</section>

      <section v-if="!isHiddenTools" class="header-btn-box flex align-center" slot="right">
        <el-badge :value="todoNum" class="icon-box margin-top-6">
          <span class="icon el-icon-s-order color-white cursor-pointer" @click="goToTodoPage"></span>
        </el-badge>

        <el-badge :value="eventAllNum" class="icon-box margin-left-right-20 margin-top-6">
          <span class="icon el-icon-message-solid color-white cursor-pointer" @click="goToEventPage"></span>
        </el-badge>

        <div class="icon-box margin-right-20 margin-top-6" v-if="$verifyPerms('enterpriseConfigPage')">
          <span class="icon el-icon-s-tools color-white cursor-pointer" @click="goToEditPage"></span>
        </div>
      </section>

      <section class="opt-btn" slot="right" v-if="$route.query.taskId && isShow">
        <el-button plain size="mini" @click="approveDo('back')">退回</el-button>
        <el-button plain size="mini" @click="approveDo('agree')">同意</el-button>
      </section>

      <section id="headerOptBtnBox" slot="right"></section>
    </base-header>

    <!-- 年度计划 -->
    <data-list :istable="false" ref="dataList"></data-list>

    <!-- 报销 -->
    <reimbursement ref="reimbursement"></reimbursement>

    <!-- 审批 -->
    <el-dialog title="审批意见" :visible.sync="approveDialogShow" width="65%" :close-on-click-modal="false" :close-on-press-escape="false">
      <form-common :filed-list="approveFiledList" ref="approveForm"></form-common>
      <div slot="footer" class="dialog-footer">
        <el-button @click="approveDialogShow = false" class="el-button-reset">取 消</el-button>
        <el-button type="primary" @click="approveFn">确 认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import Vue from 'vue';
  import { getMenuList, projectList, seletedProject, apiDoAudit, detailByTaskId, workInfoList, todoList, countUnReadNum } from '@/api';
  import filters from '@/plugins/filters/index';
  import $ from 'jquery';
  import { approveFiledList } from '@/common/js/form.js';
  import { requestTips, askDialog, getLocation } from '@/common/js/utils.js';
  import formCommon from '@g/components/form/formCommon.vue';
  import dataList from '@/pages/businessPlan/pages/businessManagementOperation/components/dataList';
  import reimbursement from '@/pages/businessAssets/modeules/reimbursement';
  import merge from 'webpack-merge';

  export default {
    name: 'Header',
    props: {
      navList: {
        type: Array,
        default: () => {
          return [];
        },
      },
      //校验navlist为空时是否调接口为其赋值
      verifyEmpty: {
        type: Boolean,
        default: false,
      },
    },
    computed: {
      isHiddenTools() {
        let pathname = location.pathname;
        let rootRoute = pathname.split('/')[1];
        return this.$route.query.isHiddenTools == 1 || !!this.navList.length || rootRoute == 'limit';
      },
      leaveType() {
        if (this.$store.state.Constants.leaveType) return this.$store.state.Constants.leaveType;
        return null;
      },
    },
    watch: {
      $route: {
        handler(val, oldval) {
          this.appName = val.query.headerName || '';
        },
        deep: true,
      },
    },
    data() {
      return {
        projectDisable: false,
        isShow: false,
        isAgree: false, //审核是否同意
        showCallDialog: false,
        callBackTime: 1,
        callType: 0,
        userInfo: {},
        projectLogo: '',
        appName: this.$route.query.headerName || '',
        dropdownList: [
          {
            value: '退出',
            label: '退出',
          },
        ],
        createEventList: [],
        menuList: [],
        projectName: '',
        projectOptions: [],
        projectMap: {},
        title: '',
        isSelectProject: false,
        approveDialogShow: false,
        approveFiledList: approveFiledList,
        notifyTimer: null,
        todoNum: 0,
        eventAllNum: 0,
      };
    },
    async created() {
      if (this.notifyTimer) {
        clearInterval(this.notifyTimer);
      }
      let systemType = getLocation(); //operationManagement:运管 assetManagement：资管
      let _this = this;
      this.detailByTaskId();
      this.name = window.yj.systemName;
      let userInfo = await window.yj.getUserInfo();
      this.userInfo = userInfo;

      // 加号按钮
      if (systemType == 'assetManagement') {
        // 资管
        this.projectLogo = require('@/common/imgs/ziguan.png');
      } else if (systemType == 'businessBuildingOperate') {
        // 商写运营
        this.projectLogo = require('@/common/imgs/businessBuildingOperate.png');
      } else {
        // 阳光数字商管
        this.projectLogo = require('@/common/imgs/yunguan.png');
      }

      if (!this.navList.length) {
        // 校验是否展示选择项目
        if (!this.isHiddenTools) {
          if (systemType == 'operationManagement') this.checkSelectProject();
          if (this.isSelectProject) {
            await this.selectList();
          }
        }

        !this.verifyEmpty && this.getMenuList();
      } else {
        this.menuList = this.navList;
      }
      if (this.$route.meta.banHeaderProject) {
        this.projectDisable = true;
      }
      $('.logo').css('width', 'auto');

      if (!this.isHiddenTools) {
        // 提醒轮询
        this.getNotifyNum();
        if (location.host.indexOf('192.168') > -1) return;
        if (!this.notifyTimer) {
          this.notifyTimer = setInterval(() => {
            this.getNotifyNum();
          }, 10000);
        }
      }
    },
    beforeDestory() {
      if (this.notifyTimer) {
        clearInterval(this.notifyTimer);
      }
    },
    methods: {
      formatDateTime: filters.formatDateTime,
      async menuRedirect(item) {
        let url = await this.$menuRedirectBaseUrl(item, {
          enterpriseid: this.$route.query.enterpriseid || localStorage.getItem('userEnterpriseid'),
        });
        window.open(url);
      },
      checkSelectProject() {
        this.isSelectProject = true;
      },
      async getMenuList() {
        let menuList = [];
        let menuData = localStorage.getItem('APP_MENU_DATA');
        if (menuData && JSON.parse(menuData) && !this.$route.query.isRefresh) {
          this.menuList = JSON.parse(menuData);
        } else {
          let res = await getMenuList({
            isSso: false,
            typeList: ['normal', 'redirect'],
            ifInMore: !this.$route.query.isRefresh ? 0 : null,
            parentId: this.$route.query.parentMenuId || sessionStorage.getItem('rootMenuId') || process.env.VUE_APP_ROOT_MENU,
            likeDescription: this.$route.query.likeDescription || null,
          });

          if (res.rows.length > 0) {
            this.menuList = res.rows;

            if (!this.$route.query.isRefresh) {
              localStorage.setItem('APP_MENU_DATA', JSON.stringify(this.menuList));
            }
          } else {
            window.location.replace('/pcError?name=not-has-role');
          }
        }
      },
      async selectList() {
        const res = await projectList({});

        this.projectOptions = res.rows;
        let projectMap = {};
        if (res.rows.length > 0) {
          const projectKey = localStorage.getItem('projectKey');
          let flag = res.rows.find(item => item.projectKey == projectKey);

          res.rows.forEach(item => {
            projectMap[item.projectKey] = item.projectName;
          });

          if (projectKey && flag) {
            this.projectName = projectKey;
          } else {
            this.projectName = res.rows[0].projectKey;
            window.location.reload();
          }
          this.changeProject();
        }

        this.projectMap = projectMap;
      },
      async changeProject(flag) {
        localStorage.setItem('projectKey', this.projectName);

        let proj = this.projectOptions.find(res => {
          return res.projectKey == this.projectName;
        });

        // 切换项目时请求接口后端保存session信息
        const res = await seletedProject({
          projectKey: this.projectName,
          roleGroupId: proj ? proj.roleGroupId : null,
        });

        this.$emit('update:setProjectKey', true);

        if (flag) {
          this.$message({
            type: 'success',
            message: '切换项目成功',
          });
          this.$router.replace({
            query: merge(this.$route.query, { projectKey: this.projectName }),
          });
          window.location.reload();
        }
      },
      handleCommand(value) {
        if (value === '退出') {
          this.handleLogout();
        }
      },
      async handleLogout() {
        await window.yj.logout();
        window.location.href = '/login';
      },
      //审批
      approveDo(type) {
        this.isAgree = type == 'agree' ? true : false;
        this.approveDialogShow = true;

        this.$nextTick(() => {
          this.$refs.approveForm.initModel();
          this.$refs.approveForm.clearValidateForm();
          this.$refs.approveForm.setFiledSource('opinionTypeName', type == 'agree' ? '是' : '否');
          this.$refs.approveForm.setFiledSource('approvalMessage', type == 'agree' ? '同意' : '不同意');
          // this.approveFiledList[0].bindFieldVal = type == 'agree' ? '是' : '否';
        });
      },
      async approveFn() {
        // askDialog('确认审批？', async () => {
        let model = this.$refs.approveForm.validateForm();
        if (!model) return;
        model.opinionType = this.isAgree ? 1 : 4; //1 同意 4拒绝
        model.userName = this.userInfo.nickname;
        model.userPrimaryKey = this.userInfo.key;
        model.businessKey = this.$route.query.processWorkId;
        model.processCode = this.$route.query.processCode;
        model.type = this.$route.query.processTypeName;
        model.typeKey = this.$route.query.processTypeKey;
        model.taskId = this.$route.query.taskId;
        model.applyUser = this.$route.query.applyUser;
        model.applyUserKey = this.$route.query.applyUserKey;
        let res = await apiDoAudit(model);
        requestTips(res, () => {
          this.approveDialogShow = false;

          setTimeout(() => {
            window.location.reload();
          }, 1000);
        });
        // });
      },
      async detailByTaskId() {
        let userInfo = JSON.parse(localStorage.getItem('userInfo'));
        if (this.$route.query.processWorkId) {
          let res = await detailByTaskId({ taskId: this.$route.query.taskId, workId: this.$route.query.processWorkId });
          if (res.state !== 'process') {
            this.isShow = false;
          } else {
            if (res.processorkey == userInfo.key) {
              //判断当前登陆人是不是即将要审批的人
              this.isShow = true;
            } else {
              this.isShow = false;
            }
          }
          this.$store.state.SubmissionButton = false;
        }
      },
      // 查询待办数量和事件数量
      async getNotifyNum() {
        let userInfo = JSON.parse(localStorage.getItem('userInfo'));

        let eventRes = await workInfoList({
          workTypeList: [1, 2],
          creatorProgressList: [1, 2],
          processorProgressList: [1, 2],
          createOrProcessorKey: userInfo.key,
          status: 1,
          neWorkStatus: 3,
          queryRelevant: true,
        });

        this.$store.state.notifyList = eventRes.rows || [];

        let todoRes = await todoList({
          currentPage: 1,
          pageSize: 1,
          action: 'todo',
        });

        this.todoNum = todoRes.total || 0;
        this.$store.state.todoNum = this.todoNum;

        let numRes = await countUnReadNum();

        this.$store.state.workNum = numRes.workTrackUnReadNum || 0;
        this.$store.state.eventNum = numRes.projectEventUnReadNum || 0;

        this.eventAllNum = this.$store.state.workNum + this.$store.state.eventNum;
      },
      goToTodoPage() {
        window.location.href = '/businessAssets/trace/home?menuId=63a745412b374be1825b38731ca55105&parentMenuId=7ee2400d0e72437aa3bdb5823497537f&tabId=ec8979570e2c4e4caf00a2ea5df4622e';
      },
      goToEventPage() {
        window.location.href = '/businessAssets/trace/traceWork?menuId=63a745412b374be1825b38731ca55105&parentMenuId=7ee2400d0e72437aa3bdb5823497537f&tabId=576171792873607168';
      },
      goToEditPage() {
        window.open('/limit/config/center?menuId=' + this.$menuId('enterpriseConfigPage'), 'enterpriseConfigPage');
      },
    },

    components: { formCommon, dataList, reimbursement },
  };
</script>

<style lang="scss" scoped>
  .header-box {
    ::v-deep .yj-base-header .logo {
      img {
        height: 26px;
        margin-right: 6px;
      }
    }

    .project-select {
      width: 120px;
      margin-right: 10px;
    }

    .opt-btn {
      margin-right: 10px;
    }

    .header-project {
      width: 100px;
      ::v-deep .el-input__inner {
        background: none;
        border: none;
        color: #fff;
      }
    }

    .header-btn-box {
      .icon-box {
        line-height: 22px;
        cursor: pointer;
      }
      .icon {
        font-size: 20px;
      }
      ::v-deep .el-badge__content {
        border: none;
        background: #ff3535 !important;
      }
    }
  }

  ::v-deep .el-button--success {
    background-color: $primary-color;
  }
  ::v-deep .el-divider--horizontal {
    margin: 10px 0 10px 0;
  }
</style>
